package com.example.demo

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.hardware.display.VirtualDisplay
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import android.widget.Button
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.getSystemService
import com.example.demo.ui.theme.MyScreenRecordDemoTheme

class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"

    private lateinit var mService: ScreenRecordService
    private var mBound: Boolean = false

    /** Defines callbacks for service binding, passed to bindService().  */
    private val connection = object : ServiceConnection {

        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance.
            val binder = service as ScreenRecordService.LocalBinder
            mService = binder.getService()
            mBound = true
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            mBound = false
        }
    }


    var mediaProjectionManager: MediaProjectionManager? = null
    var mediaProjection: MediaProjection? = null
    var virtualDisplay: VirtualDisplay? = null
    var startMediaProjection = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            mediaProjection =
                mediaProjectionManager?.getMediaProjection(result.resultCode, result.data!!)
        }
    }
    var DISPLAY_WIDTH = 0
    var DISPLAY_HEIGHT = 0
    var DISPLAY_DPI = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Bind to LocalService.
        Intent(this, ScreenRecordService::class.java).also { intent ->
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }

        mediaProjectionManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getSystemService(MediaProjectionManager::class.java)
        } else {
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager?
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val windowContext = applicationContext.createWindowContext(
                display!!,
                WindowManager.LayoutParams.TYPE_APPLICATION, null
            )
            val metrics = windowContext.getSystemService(WindowManager::class.java)
                .maximumWindowMetrics
            DISPLAY_HEIGHT = metrics.bounds.height()
            DISPLAY_WIDTH = metrics.bounds.width()
            DISPLAY_DPI = resources.configuration.densityDpi
        } else {
            val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager?
            val displayMetrics = DisplayMetrics()
            windowManager?.defaultDisplay?.getMetrics(displayMetrics)
            DISPLAY_HEIGHT = displayMetrics.heightPixels
            DISPLAY_WIDTH = displayMetrics.widthPixels
            DISPLAY_DPI = resources.configuration.densityDpi
            Log.e(TAG, "onCreate:displayMetrics DISPLAY_DPI=${displayMetrics.densityDpi} ")

        }
        Log.e(TAG, "onCreate:DISPLAY_HEIGHT=${DISPLAY_HEIGHT} ")
        Log.e(TAG, "onCreate:DISPLAY_WIDTH=${DISPLAY_WIDTH} ")
        Log.e(TAG, "onCreate:DISPLAY_DPI=${DISPLAY_DPI} ")


        findViewById<Button>(R.id.btn_action).setOnClickListener {
            startMediaProjection.launch(mediaProjectionManager?.createScreenCaptureIntent())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mBound) {
            unbindService(connection)
            mBound = false
        }
    }

}

